package com.hxs.colorfultest2.config;

import com.hxs.colorfultest2.dao.RoleDao;
import com.hxs.colorfultest2.dao.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
public class CustomerService implements UserDetailsService { //自定义UserDetailsService 接口

    @Autowired
    UserDao userDao;

    @Autowired
    RoleDao roledao;

    @Override
    public UserDetails loadUserByUsername(String username) { //重写loadUserByUsername 方法获得 userdetails 类型用户

        com.hxs.colorfultest2.domain.User user = userDao.userByName(username);
        if (user == null) {
            throw new BadCredentialsException("找不到用户信息！");
        }
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();

        String RoleName = roledao.getById(user.getRole_id());
        authorities.add(new SimpleGrantedAuthority(RoleName));


       // System.out.println(RoleName);
       // System.out.println(username);

        return new org.springframework.security.core.userdetails.User(user.getUsername(),
                user.getPassword(), authorities);




           /* System.out.println(username);
            SysUser user = userDao.userByName(username);
            if (user != null) {
                List<Permission> permissions = permissionDao.findByAdminUserId(user.getId());
                List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
                for (Permission permission : permissions) {
                    if (permission != null && permission.getName()!=null) {
                        GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getName());
                        //1：此处将权限信息添加到 GrantedAuthority 对象中，在后面进行全权限验证时会使用GrantedAuthority 对象。
                        grantedAuthorities.add(grantedAuthority);
                    }
                }
                return new User(user.getUsername(), user.getPassword(), grantedAuthorities);
            } else {
                throw new BadCredentialsException("用户名不存在!");
            }*/

    }

}
